import { message } from "antd";

let socket = new WebSocket('ws://localhost:8102/api/webrtc');

let localConnection = null;
let remoteConnection = null;

let roomId = null;
// 用户id值
let userId = null;

let remoteVideo = null;

const reconnectSocket = () => {
    if (socket.readyState !== WebSocket.OPEN) {
        console.log("尝试重新连接 WebSocket...");
        socket = new WebSocket("ws://localhost:8102/api/webrtc");
        socket.onopen = () => console.log("WebSocket 已连接");
        socket.onclose = () => console.log("WebSocket 已断开");
        socket.onerror = (error) => console.error("WebSocket 连接错误:", error);
    }
};

setInterval(reconnectSocket, 5000);

socket.onopen = () => console.log('WebSocket连接成功');
socket.onclose = () => console.log('WebSocket连接关闭');
socket.onerror = (error) => {
    console.error("WebSocket 连接错误:", error);
    reconnectSocket();
};

socket.onmessage = (event) => {
    handleSignalingMessage(JSON.parse(event.data));
}

const handleSignalingMessage = (message)=>{
    if (message.code === 400) {
        alert(message.message);  // 弹出 message 信息
        return;  // 终止后续的处理
    }
    // 根据消息的操作类型执行相应的处理
    switch (message.action) {
        case "offer":
            // 处理接收到的 offer 消息
            handleOffer(message.sdp);
            break;
        case "answer":
            // 处理接收到的 answer 消息
            handleAnswer(message.sdp);
            break;
        case "candidate":
            // 处理接收到的 candidate 消息
            handleCandidate(message.sdp);
            break;
        case "join":
            // 处理用户加入房间的消息
            console.log(`用户 ${message.userId} 加入房间 ${message.roomId}`);
            break;
        default:
            // 处理未知操作类型的消息
            console.log("未知操作:", message.action);
    }
}

const joinRoom = (roomIds: string | undefined, userIds: number | undefined) => {
    if (!roomIds) {
        message.error('房间号不能为空');
    }
    roomId = roomIds;
    userId = userIds;
    const joinMessage = {
        type: 'join',
        roomId: roomId,
        userId: userId
    };
    console.log(joinMessage)
    // 发送加入房间的信令
    //sendSignal(joinMessage.action);
    // 打印用户加入房间的信息
};



export {
    joinRoom,
    reconnectSocket,
    handleSignalingMessage
};